<?php
/*
$gtrans=new gtrans;
if ($text=$gtrans->query('Hello world','en','zh')) {
    echo $text;
} else {
    echo $gtrans->error();
}
*/
require 'httpreq.php';
class gtrans {
    private $httpreq;
    private $error;
    private $errno;
    public function __construct() {
        $this->httpreq=new httpreq;
    }  
    public function query($text, $from, $to) {
        $parameters=array(
            'v'=>'1.0',
            'q'=>$text,
            'langpair'=>$from.'|'.$to
        );
        $query_string='';
        foreach ($parameters as $k=>$v) {
            $query_string.='&'.$k.'='.urlencode($v);
        }
        $query_string=substr($query_string,0);;
        $url='http://ajax.googleapis.com/ajax/services/language/translate?'.$query_string;
        $this->httpreq->actAs(httpreq::AGENT_FIREFOX_3_5_MAC);
        $this->httpreq->setUrl($url);
        $httpres=$this->httpreq->send();
        $json_res=json_decode($httpres->body());
        if (@$json_res->responseStatus==200) {
            return $json_res->responseData->translatedText;
        } else {
            if (isset($json_res->responseStatus)) {
                $this->errno=$json_res->responseStatus;
                $this->error=$json_res->responseDetails;
            } else {
                $this->errno=0;
                $this->error='err: http status: '.$httpres->status();
            }
            return false;
        }
    }
    public function error() {
        return $this->error;
    }
    public function errno() {
        return $this->errno;
    }
}
